package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName TrackReceiver
 * @description: TODO
 * @date 2024年04月19日
 * @version: 1.0
 */
@Component
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 修改声音播放数据
     * @param record
     * @return
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void updateTrackStat(ConsumerRecord<String,String> record){
        //  获取json 数据
        String strJson = record.value();
        //  将这个数据转化为对象
        TrackStatMqVo trackStatMqVo = JSON.parseObject(strJson, TrackStatMqVo.class);
        //  封装了一个业务编号.利用业务编号防止重复消费.
        String key = trackStatMqVo.getBusinessNo();
        //  判断这个业务编号在缓存中是否存在.
        Boolean result = this.redisTemplate.opsForValue().setIfAbsent(key, 1, 3, TimeUnit.MINUTES);
        //  result=true; 第一次执行. result=false; 说这个消息已被消费过.
        if (result){
            try {
                //  调用服务层方法. update track_stat set stat_num = ? where stat_typ=? track_id=?
                trackInfoService.updateTrackStat(trackStatMqVo);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                this.redisTemplate.delete(key);
            }
        }
    }
}
